//
// Created by nilyang on 2021/11/25.
//

#include "file_handlers.h"
#include <cstdlib>
#include <sys/stat.h>
#include <memory>
#include <cstring>
FileHandler::FileHandler(const char *name, const char *mod) :
        permits(nullptr), filename(nullptr), pf(nullptr) {
    size_t fnsize = strlen(name);
    filename = new char[fnsize + 1];
    std::memcpy(filename, name, fnsize + 1);

    pf = std::fopen(filename, mod);
    if (pf)
        std::cout << "success: opened file:" << filename << std::endl;
    else
        std::cout << "failed: opened file:" << filename << std::endl;
}

FileHandler::~FileHandler() {
    if (pf) {
        std::fclose(pf);
        delete[] filename;
    }
    pf = nullptr;
    filename = nullptr;
}

void FileHandler::Write(const std::string &text) {
    if (pf) {
        char* str = new char[(text.size() +1)];
        std::strcpy(str, text.c_str());
        str[text.size()] = '\n';
        int x = fputs(str, pf);
        std::cout << "\nSUCCESS:save: " << x << ",text=`" << text << " ` to file :  " << filename << std::endl;
        delete[] str;
        str = nullptr;
    } else {
        std::cout << "\nFAILED:save ` " << text << " ` to file :  " << filename << std::endl;
    }
}

void FileHandler::Write(const char *text) {
    Write(std::string(text));
}

void func_test_file() {
    const char *filename = "./runtime/test.log";
    const char *dir = "./runtime/";
    if (!mkdir(dir, 0755)) {
        std::cout << "Fail: make dir" << std::endl;
    }
    FileHandler handler(filename);
    handler.Write("Hello world!");
    filename = nullptr;
}
